package com.bingxue.edu.management.system.service;

import cn.dev33.satoken.dao.SaTokenDao;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.bingxue.edu.management.auth.EmployeeAuthUtil;
import com.bingxue.edu.management.auth.model.AuthEmployee;
import com.bingxue.edu.management.system.model.query.OnlineUserQuery;
import com.bingxue.edu.management.system.model.resp.OnlineUserResp;
import com.bingxue.edu.framework.common.model.PageQuery;
import com.bingxue.edu.framework.common.model.Pagination;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @author panbo
 * @since 2024/8/27
 */
@Service
public class OnlineUserService {

    public Pagination<OnlineUserResp> page(OnlineUserQuery query, PageQuery pageQuery) {
        List<AuthEmployee> loginUserList = this.list(query);
        List<OnlineUserResp> list = BeanUtil.copyToList(loginUserList, OnlineUserResp.class);
        return Pagination.of(pageQuery.getPage(), pageQuery.getSize(), list);
    }

    public List<AuthEmployee> list(OnlineUserQuery query) {
        List<AuthEmployee> loginUserList = new ArrayList<>();
        // 查询所有登录用户
        List<String> tokenKeyList = EmployeeAuthUtil.STP.searchTokenValue(StrUtil.EMPTY, 0, -1, false);
        for (String tokenKey : tokenKeyList) {
            String token = StrUtil.subAfter(tokenKey, StrUtil.COLON, true);
            // 忽略已过期或失效 Token
            if (EmployeeAuthUtil.STP.getTokenActiveTimeoutByToken(token) < SaTokenDao.NEVER_EXPIRE) {
                continue;
            }
            // 检查是否符合查询条件
            AuthEmployee authUser = EmployeeAuthUtil.getAuthUser(token);
            if (this.isMatchQuery(query, authUser)) {
                loginUserList.add(authUser);
            }
        }
        // 设置排序
        CollUtil.sort(loginUserList, Comparator.comparing(AuthEmployee::getLoginTime).reversed());
        return loginUserList;
    }

//    public LocalDateTime getLastActiveTime(String token) {
//        long lastActiveTime = EmployeeAuthUtil.STP.getStpLogic().getTokenLastActiveTime(token);
//        return lastActiveTime == SaTokenDao.NOT_VALUE_EXPIRE ? null : DateUtil.date(lastActiveTime).toLocalDateTime();
//    }
//
//    public void cleanByRoleId(Long roleId) {
//        List<AuthEmployee> loginUserList = this.list(new OnlineUserQuery());
//        loginUserList.parallelStream().forEach(u -> {
//            if (u.getRoles().stream().anyMatch(r -> r.getId().equals(roleId))) {
//                try {
//                    EmployeeAuthUtil.STP.logoutByTokenValue(u.getToken());
//                } catch (NotLoginException ignored) {
//                }
//            }
//        });
//    }

    public void cleanByUserId(Long userId) {
        if (!EmployeeAuthUtil.STP.isLogin(userId)) {
            return;
        }
        EmployeeAuthUtil.STP.logout(userId);
    }

    /**
     * 是否符合查询条件
     *
     * @param query     查询条件
     * @param authUser 登录用户信息
     * @return 是否符合查询条件
     */
    private boolean isMatchQuery(OnlineUserQuery query, AuthEmployee authUser) {
        boolean flag1 = true;
        String name = query.getName();
        if (StrUtil.isNotBlank(name)) {
            flag1 = StrUtil.contains(authUser.getUserInfo().getName(), name);
        }

        boolean flag2 = true;
        List<Date> loginTime = query.getLoginTime();
        if (CollUtil.isNotEmpty(loginTime)) {
            flag2 = DateUtil.isIn(DateUtil.date(authUser.getLoginTime()).toJdkDate(), loginTime.get(0), loginTime.get(1));
        }
        return flag1 && flag2;
    }
}

